<?php
/**
 * JoomFish quick translate - JoomFish! translation on the fly
 *
 * @author Hnat Kubov
 * @version 0.1
 * @authoremail hnatt88@gmail.com
 * @license GNU/GPL http://www.gnu.org/licenses/gpl-2.0.htm
 * @package joomfish
 * @subpackage admin.jfdatabase_bot
 */

// TODO: make work with Joomla 1.5 for future

// direct access restriction
defined('_VALID_MOS') or die(); 

// if no JoomFish installed or we are currently
// on one of JoomFish backend pages, then just quit
$compPath = JPATH_BASE_ADMIN.DS.'components'.DS.'com_joomfish'.DS;
if (!file_exists($compPath.'joomfish.class.php')
	|| mosGetParam($_REQUEST, 'option') == 'com_joomfish') {
	return;
}

// exit if it's JPromoter page to prevent Jommla 1.5 classes redeclaration
if (mosGetParam($_REQUEST, 'option') == 'com_jp') {
	return;
}


$_MAMBOTS->registerFunction('onAfterAdminStart','JFQuickTranslateDispatch');
$_MAMBOTS->registerFunction('onBeforeAdminOutput','JFQuickTranslateDispatch');
$_MAMBOTS->registerFunction('onAfterAdminAjaxStart','JFQuickTranslateDispatch');

// include component files. Looks ugly, but what can you do?
include_once $compPath.'joomfish.class.php';
include_once $compPath.'admin.joomfish.html.php';
include_once $compPath.'controler.php';
// If this is not Joomla 1.5, and 1.5 classes are not declared elsewhere
// then load these classes from JoomFish directory
if(!class_exists("JLanguage")) {
	include_once $compPath.'libraries'.DS.'joomla'.DS.'language.php';
}
if(!class_exists("JRegisrty")) {
	include_once $compPath.DS.'libraries'.DS.'joomla'.DS.'registry.php';
}
include_once JPATH_BASE.DS.'components'.DS.'com_joomfish'.DS
	.'includes'.DS.'defines.php';

function JFQuickTranslateDispatch() {
	$mainframe = mosMainFrame::getInstance();
	$db = $mainframe->getDBO();

	// Create JoomFishManager and put it to the GLOBALS (required by controler)
	$joomFishManager = new JoomFishManager();
	$GLOBALS['joomFishManager'] = & $joomFishManager;

	// Get list of JoomFish content elements
	$contentElements = array_keys($joomFishManager->getContentElements());

	// in order to make it work in AJAX requests, need to manually specify
	// 'task' in $_REQUEST
	if ($task = mosGetParam($_GET, 'task')) {
		if(mosGetParam($_REQUEST, 'task') != $task) {
			$_REQUEST['task'] = $task;
		}
	}

	// Read configuration and define with actions to perform on this page
	$requiredActions = JFQuickTranslateReadConfig($contentElements);

	// Put them to $GLOBALS
	$GLOBALS['JFQT_RequiredActions'] = $requiredActions;

	if(key_exists('save', $requiredActions)) {
		JFSaveTranslations($joomFishManager);
	}

	// If 'edit' action required, then render and integrate
	// the translation forms
	if(key_exists('edit', $requiredActions)) {
		$catid = $requiredActions['edit']['catid'];
		$possibleIds = explode('|', $requiredActions['edit']['contentid']);
		$contentid = null;
		foreach($possibleIds as $paramName) {
			if ($contentid = mosGetParam($_REQUEST, $paramName)) {
				if(is_array($contentid)) {
					$contentid = $contentid[0];
				}
				break;
			}
		}
		if($contentid) {
			JFQT_TranslationForms($catid, $contentid);
		}
	}

}

/**
 * Compare current request with mambot configuration to check if there are
 * any actions to perform on current page
 * @param Array $contentElements
 * @return Array required action 
 */
function JFQuickTranslateReadConfig($contentElements) {

	// Read XML config
	$xmlString = file_get_contents(JPATH_BASE.'/mambots/admin/'
			.'jf_quick_translate/config.xml');
	$xml = new SimpleXMLElement($xmlString);
	$contentElementsConfig = $xml->content_elements;

	// And make it look like that:
	//	stdClass Object
	//	{
	//    [sv_videos] => stdClass Object
	//        (
	//            [request_params_edit] => Array
	//                (
	//                    [0] => stdClass Object
	//                        (
	//                            [option] => com_simplevideo
	//                            [task] => edit
	//                        )
	//
	//                )
	//            [contentid] => cid
	//            [request_params_save] => Array
	//                (
	//                    [0] => stdClass Object
	//                        (
	//                            [option] => com_simplevideo
	//                            [task] => save|apply
	//                        )
	//
	//                )
	//        )
	//	)
	//

	$config = new stdClass();

	foreach($contentElementsConfig->element as $element) {
		$attribs = $element->attributes();
		$catid = (string)$attribs['name'];
		$contentid = (string)$attribs['contentid'];
		$requestParams = array();
		foreach(array('edit','save') as $action) {
			$i = 0;
			$requestParams[$action] = array();
			$fieldName = $action.'_request_params';
			foreach($element->$fieldName->set as $set) {
				$paramsSet = array();
				foreach($set->param as $param) {
					$attribs = $param->attributes();
					$paramsSet[(string)$attribs['name']] =
						(string)$attribs['value'];
				}
				$requestParams[$action][$i++] = (object)$paramsSet;
			}
		}
		$config->$catid = (object)array(
			'request_params_edit' => $requestParams['edit'],
			'contentid' => $contentid,
			'request_params_save' => $requestParams['save']
		);
	}

	$requiredActions = array();
	// Check every JF content element to find out if we need JoomFish actions
	// on current page
	foreach($contentElements as $catid) {
		if(isset($config->$catid)) {
			$elementParams = $config->$catid;
			// Currently, possible actions are:
			//   'edit' -- intergrate the translation forms to current page
			//   'save' -- process submitted translation forms
			foreach(array('edit','save') as $action) {
				$needAction = false;
				$fieldName = "request_params_$action";
				foreach($elementParams->$fieldName as $requestParams) {
					// Let's suppose that all request parameters match with
					// those in $requestParams. Then find out if it's true
					$allParametersMatch = true;
					// Check every key-value paur in $requestParams
					foreach($requestParams as $paramName => $paramValue) {
						$possibleParamValues = explode('|', $paramValue);
						// If one of the parameters has different value in
						// $_REQUEST or is not defined, then this $requestParams
						// does not match the current page
						if(!in_array(mosGetParam($_REQUEST, $paramName),
								$possibleParamValues)) {
							$allParametersMatch = false;
							break;
						}
					}
					// If, after all, the $allParametersMatch remained 'true',
					// then all parameters DID match, and current page needs
					// JoomFish action
					$needAction = $allParametersMatch;
					// if we found out that page needs action, then no need
					// to find further
					if($needAction) break;
				}
				// if we need action on the page, then remember fields of
				// current $elementParams
				if($needAction) {
					$requiredActions[$action] = array(
							'catid' => $catid,
							'contentid' => $elementParams->contentid
						);
				}
			}
		}
	}

	return $requiredActions;
}

function JFSaveTranslations($joomFishManager) {
	// Activate language pack for JoomFish
	$adminLang = strtolower(
		$joomFishManager->getCfg('componentAdminLang')
	);
	$lang =& JLanguageHelper::getLanguage($adminLang);
	$lang->load( 'com_joomfish', JOOMFISH_LANGPATH );

	// create JoomFish controller
	$JFControler = new JoomfishControler();
	// back up the post data
	$old_POST = $_POST;
	$activeLanguages = $joomFishManager->getActiveLanguages();
	foreach($activeLanguages as $code => $language) {
		if(key_exists("jf_$code", $old_POST)) {
			$_POST = $old_POST["jf_$code"];
			$language_id = mosGetParam($_POST, 'language_id');
			$catid = mosGetParam($_POST, 'catid');
			$JFControler->saveTranslation($language_id, $catid, null, null);
		}
	}
	// recover post data
	$_POST = $old_POST;
}


function JFQT_TranslationForms($catid, $contentid) {
	$mainframe = mosMainFrame::getInstance();

	// Create JoomFishManager and put it to the GLOBALS (required by controler)
	$joomFishManager = new JoomFishManager();
	$GLOBALS['joomFishManager'] = & $joomFishManager;

	global $_MAMBOTS;
	mosCommonHTML::loadJquery();
	mosCommonHTML::loadJqueryPlugins('jquery.form');
	require_once JPATH_BASE.DS.'includes'.DS.'editor.php';

	// Activate language pack for JoomFish
	$adminLang = strtolower(
		$joomFishManager->getCfg('componentAdminLang')
	);
	$lang =& JLanguageHelper::getLanguage($adminLang);
	$lang->load( 'com_joomfish', JOOMFISH_LANGPATH );

	// Create JoomFish controller
	$JFControler = new JoomfishControler();

	$active_languages = $joomFishManager->getActiveLanguages();
	$pages = array();
	// Render translation edit pages for each active language and display
	// them in hidden blocks
	foreach($active_languages as $code => $language) {
		if($code != $mainframe->lang) {
			$lang_codes[] = $code;
			ob_start();
			$JFControler->editTranslation(null, $language->id, $catid,
					$contentid, $language->id);
			$page = ob_get_contents();
			ob_end_clean();
			// replace form name and div id
			$page = str_replace('adminForm', "adminForm_jf_$code",
					$page);
			$page = str_replace('div id="joomfish"',
					"div id=\"joomfish_$code\" style=\"display: none\"",
					$page);
			// disable or fix scripts that causing errors
			$page = preg_replace('/<script.*tabPane.*<\/script>/U',
					'', $page);
			$page = preg_replace('/<script.*tabpane.js.*<\/script>/U',
					'', $page);
			$page = preg_replace('/<link.*tabpane.css.*\/>/U',
					'', $page);
			$page = str_replace('submitbutton', 'submitbutton_'.$code,
					$page);
			// remove maxlength attributes
			$page = preg_replace('/maxlength=\"[0-9]+\"/', '', $page);
			// Create unique id's for textareas to make editor render
			// for each one
			$page = preg_replace('/(<textarea.* id=\")(.*)(\".*'
					.'<\/textarea>)/U', '$1$2_'.$code.'$3', $page);

			$pages[] = $page;
		}
	}

	ob_start();

	// create a script for navigation between translations and a hook
	// for Save event
?>
<link rel="stylesheet" type="text/css" media="all" href="<?php echo JPATH_SITE; ?>/administrator/templates/joostfree/css/tabpane.css" id="luna-tab-style-sheet" />
<script type="text/javascript" src="<?php echo JPATH_SITE; ?>/includes/js/tabs/tabpane.js"></script>
<style type="text/css">
	ul.jf_tabs {
		margin: 10px 0 0 10px;
		padding: 10px 0 5px 15px;
		background: url('<?php echo JPATH_SITE; ?>/administrator/modules/mod_translate.png') left center no-repeat;
		border-bottom: 2px #ccc solid;
	}
	.jf_tabs li {
		cursor: pointer;
		border: 1px #ccc solid;
		padding: 5px;
		list-style: none;
		display: inline;
	}
	.jf_tabs li.active {
		border-width: 2px;
		padding-top: 8px;
		border-bottom-color: #fff;
		font-weight: bold;
	}
</style>
<script type="text/javascript">
	var jf_langs = <?php echo json_encode($lang_codes); ?>;

	function copyFields() {
		$('form[name^=adminForm_jf_]').each(function(){
			var langcode = $(this).attr('name').substr(13);
			$('form[name=adminForm] #jf_hidden_'+langcode).remove();
			$('form[name=adminForm]').append('<div id="jf_hidden_'+langcode+'" style="display: none;"></div>');
			$(this).find('input,select,textarea').each(function(){
				var name = $(this).attr('name');
				var value = $(this).val();
				value = value.replace(/"/g, '&quot;');
				if(name) {
					if(($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio') && !$(this).attr('checked'))
						return;
					else
						var field = '<input type="hidden" name="jf_'+langcode+'['+name+']" '
								+'value="'+value+'" />';
						$('#jf_hidden_'+langcode).append(field);
				}
			});
		});
		if(tinyMCE) {
			tinyMCE.triggerSave();
		}
	}

	$(document).ready(function(){
		$('#toolbar').mousedown(copyFields);
		$('#toolbar .tb-save,#toolbar #tb-apply').mousedown(copyFields);
		$('#main_body').before('<ul class="jf_tabs">Translation: <li class="active original">original</li><li class="translation"><?php echo join('</li><li class="translation">', $lang_codes); ?></li></ul>');
		$('.jf_tabs li.translation').click(function(){
			$('form[name=adminForm]').hide();
			$('div[id^=joomfish]').hide();
			$('#joomfish_'+$(this).html()).show();
			$('.jf_tabs li').removeClass('active');
			$(this).addClass('active');
		});
		$('.jf_tabs li.original').click(function(){
			$('div[id^=joomfish]').hide();
			$('form[name=adminForm]').show();
			$('.jf_tabs li').removeClass('active');
			$(this).addClass('active');
		});
		$('[id=ItemInfo-page]').each(function(){
			if($(this).html().indexOf('New') >= 0) {
				$(this).find('input').attr('checked', 'true');
			};
		});
	});
</script>
<?php

	foreach($pages as $page) echo $page;

	$forms = ob_get_contents();
	ob_end_clean();

	global $_MOS_OPTION;
	$_MOS_OPTION['buffer'] = $forms . $_MOS_OPTION['buffer'];
	
}